package com.dkd.system.service.impl;

import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.dkd.common.constant.DkdContants;
import com.dkd.common.exception.ServiceException;
import com.dkd.common.utils.DateUtils;
import com.dkd.system.domain.*;
import com.dkd.system.domain.vo.TbTaskVo;
import com.dkd.system.service.ITbEmpService;
import com.dkd.system.service.ITbTaskDetailsService;
import com.dkd.system.service.ITbVendingMachineService;
import javafx.concurrent.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.dkd.system.mapper.TbTaskMapper;
import com.dkd.system.service.ITbTaskService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 工单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-29
 */
@Service
public class TbTaskServiceImpl implements ITbTaskService 
{
    @Resource
    private TbTaskMapper tbTaskMapper;

    /**
     * 查询工单
     * 
     * @param taskId 工单主键
     * @return 工单
     */
    @Override
    public TbTask selectTbTaskByTaskId(Long taskId)
    {
        return tbTaskMapper.selectTbTaskByTaskId(taskId);
    }

    /**
     * 查询工单列表
     * 
     * @param tbTask 工单
     * @return 工单
     */
    @Override
    public List<TbTaskVo> selectTbTaskList(TbTask tbTask)
    {
        return tbTaskMapper.selectTbTaskList(tbTask);
    }

    /**
     * 新增工单
     * 
     * @param tbTask 工单
     * @return 结果
     */
    @Override
    public int insertTbTask(TbTask tbTask)
    {
        tbTask.setCreateTime(DateUtils.getNowDate());
        return tbTaskMapper.insertTbTask(tbTask);
    }

    /**
     * 修改工单
     * 
     * @param tbTask 工单
     * @return 结果
     */
    @Override
    public int updateTbTask(TbTask tbTask)
    {
        tbTask.setUpdateTime(DateUtils.getNowDate());
        return tbTaskMapper.updateTbTask(tbTask);
    }

    /**
     * 批量删除工单
     * 
     * @param taskIds 需要删除的工单主键
     * @return 结果
     */
    @Override
    public int deleteTbTaskByTaskIds(Long[] taskIds)
    {
        return tbTaskMapper.deleteTbTaskByTaskIds(taskIds);
    }

    /**
     * 删除工单信息
     * 
     * @param taskId 工单主键
     * @return 结果
     */
    @Override
    public int deleteTbTaskByTaskId(Long taskId)
    {
        return tbTaskMapper.deleteTbTaskByTaskId(taskId);
    }
   @Autowired
   private ITbVendingMachineService tbVendingMachineService;
    @Resource
    private TbTaskMapper taskMapper;
    @Resource
    private ITbEmpService empService;

    @Autowired
    private ITbTaskDetailsService tbTaskDetailsService;
    @Transactional
    public int insertTaskDto(TaskDto taskDto){
        //查询售货机是否存在
        TbVendingMachine tbVendingMachine=tbVendingMachineService.selectVendingMachineByInnerCode(taskDto.getInnerCode());
        if(tbVendingMachine == null){
            throw new ServiceException("设备不存在");
        }
        //校验售货机状态与工单类型是否相符
        checkCreatecode(tbVendingMachine.getVmStatus(),taskDto.getProductTypeId());
        //检查设备中是否有未完成的同类型的工单
        TbTask taskParam=new TbTask();
        taskParam.setInnerCode(taskDto.getInnerCode());
        taskParam.setProductTypeId(taskDto.getProductTypeId());
        taskParam.setTaskStatus(DkdContants.TASK_STATUS_PROGRESS);
        List<TbTask> list=taskMapper.selectTaskList(taskParam);
        if(list.size()>0 &&list!=null){
            throw new ServiceException("该设备中有未完成的工单");

        }
        //查询员工是否存在

       TbEmp tbEmp= empService.selectEmpById(taskDto.getUserId());
        if(tbEmp == null){
            throw new ServiceException("员工不存在");
        }

        //检验员工区域是否匹配
        if(!tbEmp.getRegionId().equals(tbVendingMachine.getRegionId())){
            throw new ServiceException("员工区域与设备区域不一致");

        }

       TbTask task= BeanUtil.copyProperties(taskDto,TbTask.class);
        task.setTaskStatus(DkdContants.TASK_STATUS_CREATE);
        task.setTaskStatus(DkdContants.TASK_STATUS_CREATE);
        task.setUserName(tbEmp.getUserName());
        task.setRegionId(tbVendingMachine.getRegionId());
        task.setAddr(tbVendingMachine.getAddr());
        task.setCreateTime(DateUtils.getNowDate());
        task.setTaskCode(generateTaskCode());
        int taskRes=taskMapper.insertTask(task);
        if(taskDto.getProductTypeId().equals(DkdContants.TASK_TYPE_SUPPLY)){
            List<TaskDetailsDto> details=taskDto.getDetails();
            CollUtil.isEmpty(details);
            if(CollUtil.isEmpty(details)){
               throw new ServiceException("补货工单详情不能为空");
            }
          List<TbTaskDetails> list1=details.stream().map(dto->{
                TbTaskDetails taskDetails=BeanUtil.copyProperties(dto,TbTaskDetails.class);
                taskDetails.setTaskId(task.getTaskId());
                return taskDetails;
            }).collect(Collectors.toList());
            //批量新增
            tbTaskDetailsService.batchInsertTaskDetails(list1);

        }




       return taskRes;

    }
    @Resource
    private RedisTemplate redisTemplate;
    //生成获取当天工单编号
    private String generateTaskCode(){
        String dateStr=DateUtils.getDate().replaceAll("-","");
        String key="dkd.task.code."+dateStr;
        if(!redisTemplate.hasKey(key)){
            redisTemplate.opsForValue().set(key,1, Duration.ofDays(1));
            return dateStr+"0001";
        }
       return dateStr+ StrUtil.padPre(redisTemplate.opsForValue().increment(key).toString(),4,"0");



    }
    //校验售货机状态与工单类型是否相符
    private  void checkCreatecode(Long vmStatus,Long productTypeId){
        //如果是投放工单，设备运行中，抛出异常

        if(productTypeId == DkdContants.TASK_TYPE_DEPLOY &&vmStatus == DkdContants.VM_STATUS_RUNNING){
            throw new ServiceException("该设备状态为运行中，无法进行投放");
        }
        //如果是维修工单，设备不在运行中，排除异常
        if(productTypeId == DkdContants.TASK_TYPE_REPAIR &&vmStatus != DkdContants.VM_STATUS_RUNNING){
            throw new ServiceException("该设备状态不为运行中，无法进行维修");
        }
        //如果是补货工单，设备不在运行中，排除异常
        if(productTypeId == DkdContants.TASK_TYPE_SUPPLY &&vmStatus != DkdContants.VM_STATUS_RUNNING){
            throw new ServiceException("该设备状态不为运行中，无法进行补货");
        }
        //如果是撤机工单，设备不在运行中，排除异常
        if(productTypeId == DkdContants.TASK_TYPE_REVOKE &&vmStatus != DkdContants.VM_STATUS_RUNNING){
            throw new ServiceException("该设备状态不为运行中，无法进行撤机");
        }
    }
    public int cancelTbTask(TbTask task){
        System.out.println(task);
TbTask task1=tbTaskMapper.selectTbTaskByTaskId(task.getTaskId());
if(task1.getTaskStatus().equals(DkdContants.TASK_STATUS_FINISH)){
    throw new ServiceException("该订单已完成，不能取消");

}
        if(task1.getTaskStatus().equals(DkdContants.TASK_STATUS_CANCEL)){
            throw new ServiceException("该订单已取消，不能取消");

        }
        task1.setTaskStatus(DkdContants.TASK_STATUS_CANCEL);
        task1.setUpdateTime(DateUtils.getNowDate());
       int result= taskMapper.updateTbTask(task1);
        return result;

    }

}
